package com.example.springboot2.xdkt.controller;

import com.example.springboot2.xdkt.domain.JsonData;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 功能描述:跳转到静态资源,要实现这个功能，需要添加templates模板
 */
@Controller
public class FileController {

    @RequestMapping(value = "/api/v1/gopage")
    public Object index() {
        //这里会根据名字映射到templates文件
        return "index";
    }

    @RequestMapping(value = "/api/v1/goupload")
    public Object upload() {
        //这里会根据名字映射到templates文件
        return "upload";
    }


    /**
     * 文化上传
     */
    private static final String filePath = "d:\\upload\\";

    @RequestMapping(value = "upload")
    @ResponseBody
    public JsonData upload(@RequestParam("head_img")MultipartFile file, HttpServletRequest request) {

        String name = request.getParameter("name");

        System.out.println("用户名:" + name);

        //获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为:" + fileName);

        //获取文件后缀名,substring是根据索引截取后面的字段，lastIndexOf是获取索引
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println(suffixName);

        //文件上传后的路径
        fileName = UUID.randomUUID() + suffixName;
        System.out.println("转换后的名称:" + fileName);
        File file1 = new File(filePath);
        boolean absolute = file1.isDirectory();
        File dest = null;
        if(absolute) {
            dest = new File(filePath + fileName);
        }else {
            file1.mkdir();
        }


        try {
            file.transferTo(dest);

            return new JsonData(0, fileName);
//            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new JsonData(-1, "上传失败");
    }


}
